package com.collectplus.express.menu;

import android.content.Intent;
import android.os.Bundle;
import android.os.Message;
import android.text.Editable;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;

import com.collectplus.express.BaseActivity2;
import com.collectplus.express.R;
import com.collectplus.express.logic.AppCache;
import com.collectplus.express.logic.AppHttp;
import com.collectplus.express.logic.AppResult;
import com.collectplus.express.logic.JSON;
import com.collectplus.express.logic.MsgID;
import com.collectplus.express.tools.TextWatcherExt;

/**
 * 修改用户名
 * 
 * @author coffee<br>
 *         2015-6-18下午5:08:53
 */
public class EditNameActivity extends BaseActivity2 implements OnClickListener {

	private EditText mNameEdit;
	private Button mOKButton;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
	}

	@Override
	protected void findViewById() {
		setContentView(R.layout.edit_name);
		super.findViewById();
		getAppTitle().setCommonTitle("修改昵称");
		mOKButton = (Button) findViewById(R.id.edit_name_ok_button);
		mOKButton.setOnClickListener(this);
		setButtonEnableStyle(mOKButton, false);
		//
		mNameEdit = (EditText) findViewById(R.id.edit_name_edittext);
		mNameEdit.addTextChangedListener(new TextWatcherExt() {
			@Override
			public void afterTextChanged(Editable s) {
				if (s.toString().trim().length() > 0) {
					setButtonEnableStyle(mOKButton, true);
				} else {
					setButtonEnableStyle(mOKButton, false);
				}
			}
		});
		String name = getIntent().getStringExtra("item");
		mNameEdit.setText(name);
		setCursorToLast(mNameEdit);
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.edit_name_ok_button:
			String name = mNameEdit.getText().toString();
			if (TextUtils.isEmpty(name.trim())) {
				showToast("请填写您的姓名");
				return;
			}
			showLoadingDialog(null);
			AppHttp.getInstance().editUserName(name);
			break;
		}
	}

	public boolean handleMessage(Message msg) {
		switch (msg.what) {
		case MsgID.editUserName:
			cancelLoadingDialog();
			AppResult<?> deleteResult = JSON.parser(msg.obj);
			if (deleteResult == null) {
				return true;
			}
			switch (deleteResult.getStatus()) {
			case 1:
				showToast("修改成功");
				AppCache.setUserName(mNameEdit.getText().toString());
				Intent dsta = new Intent();
				dsta.putExtra("nickname", mNameEdit.getText().toString());
				setResult(RESULT_OK, dsta);
				finish();
				break;
			case 0:
				showToast(deleteResult.getMessage());
				break;
			}
			break;
		}
		return true;
	}

}
